<?php

namespace Luka\SecurityBundle\Authentication;

use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Doctrine\ORM\EntityManager;

//http://symfony.com/doc/current/cookbook/security/entity_provider.html
class PartyUserProvider  /*extends EntityRepository*/ implements UserProviderInterface {
    private $em;

    public function __construct(EntityManager $em) {
        $this->em = $em;
    }

    public function loadUserByUsername($username) {
        echo($username);
        /*$q = $this
            ->createQueryBuilder('u')
            ->where('u.username = :username')
            ->setParameter('username', $username)
            ->getQuery();

        try {
            $user = $q->getSingleResult();
        } catch (NoResultException $e) {
            throw new UsernameNotFoundException(sprintf('Unable to find an active user object identified by "%s".', $username), null, 0, $e);
        }

        return $user;

        */

        // make a call to your webservice here
        $userData = false;
        // pretend it returns an array on success, false if there is no user

        if ($userData) {
            //$password = '...';

            // ...
            $password ="";
            $salt ="";
            $roles = array();
            return new PartyUser($username, $password, $salt, $roles);
        } else {
            throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
        }
    }

    public function refreshUser(UserInterface $user) {
        $class = get_class($user);
        if (!$this->supportsClass($class)) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', $class));
        }
        return $this->loadUserByUsername($user->getUsername());
    }

    public function supportsClass($class){
        return $this->getEntityName() === $class || is_subclass_of($class, $this->getEntityName());
    }
}
